import random
from .forms import UserInfoUpdateForm
from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login as auth_login
from django.views.decorators.csrf import csrf_exempt
from django.db.models import F
from .models import UserInfo, Type, Collect
from .forms import CaptchaForm, LoginForm
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import UserInfoSerializer
from django.shortcuts import get_object_or_404
from django.http import JsonResponse
from .models import Video, Like


@csrf_exempt
def collect_video(request):
    username = request.POST.get('username')
    video_id = request.POST.get('video_id')
    if not username or not video_id:
        return JsonResponse({'status': 'error', 'message': 'Missing username or video_id'}, status=400)

    video = get_object_or_404(Video, id=video_id)
    user = get_object_or_404(UserInfo, username=username)
    collect, created = Collect.objects.get_or_create(username=user, item_id=video)

    if created:
        return JsonResponse({'code':200,'status': 'collected'})
    else:
        return JsonResponse({'status': 'already_collected'})

@csrf_exempt
def uncollect_video(request):
    username = request.POST.get('username')
    video_id = request.POST.get('video_id')
    if not username or not video_id:
        return JsonResponse({'status': 'error', 'message': 'Missing username or video_id'}, status=400)

    video = get_object_or_404(Video, id=video_id)
    user = get_object_or_404(UserInfo, username=username)
    collect = Collect.objects.filter(username=user, item_id=video).first()
    if collect:
        collect.delete()
        return JsonResponse({'code':200,'status': 'uncollected'})
    else:
        return JsonResponse({'status': 'not_collected'})

#点赞视频
@csrf_exempt
def like_video(request):
    username = request.POST.get('username')
    video_id = request.POST.get('video_id')
    if not username or not video_id:
        return JsonResponse({'status': 'error', 'message': 'Missing username or video_id'}, status=400)

    video = get_object_or_404(Video, id=video_id)
    user = get_object_or_404(UserInfo, username=username)  # 获取用户实例
    like, created = Like.objects.get_or_create(username=user, item_id=video)

    if created:
        video.agreeNumber += 1
        video.save()
        return JsonResponse({'code':200,'status': 'liked', 'agreeNumber': video.agreeNumber})
    else:
        return JsonResponse({'status': 'already_liked'})

#取消点赞视频
@csrf_exempt
def unlike_video(request):
        username = request.POST.get('username')
        video_id = request.POST.get('video_id')
        if not username or not video_id:
            return JsonResponse({'status': 'error', 'message': 'Missing username or video_id'}, status=400)

        video = get_object_or_404(Video, id=video_id)
        user = get_object_or_404(UserInfo, username=username)
        like = Like.objects.filter(username=user, item_id=video).first()
        if like:
            like.delete()
            video.agreeNumber -= 1
            video.save()
            return JsonResponse({'code':200,'status': 'unliked', 'agreeNumber': video.agreeNumber})
        else:
            return JsonResponse({'status': 'not_liked'})


def liked_videos(request):
    username = request.GET.get('username')
    if not username:
        return JsonResponse({"code": 400, "message": "请求失败，参数错误"})

    user = get_object_or_404(UserInfo, username=username)

    try:
        liked_videos = list(
            Video.objects.filter(like__username=user)
            .annotate(annotated_type_nameid=F('type_nameid__nameid'))
            .values('id', 'ctime', 'title', 'description', 'source', 'picUrl', 'url', 'commitNumber',
                    'agreeNumber', 'watched', 'type_nameid')
        )
        liked_videos = [
            {**video,
             'picUrl': f"/media/{video['picUrl']}",
             'url': f"/media/{video['url']}",
             'is_liked': Like.objects.filter(username=user, item_id=video['id']).exists(),
             'is_collected': Collect.objects.filter(username=user, item_id=video['id']).exists(),
             }
            for video in liked_videos
        ]
        return JsonResponse({"code": 200, "message": "请求成功", "liked_videos": liked_videos})
    except Exception as e:
        return JsonResponse({"code": 500, "message": f"请求失败，服务器错误: {str(e)}"})

def collected_videos(request):
    username = request.GET.get('username')
    if not username:
        return JsonResponse({"code": 400, "message": "请求失败，参数错误"})

    user = get_object_or_404(UserInfo, username=username)

    try:
        collected_videos = list(
            Video.objects.filter(collect__username=user)
            .annotate(annotated_type_nameid=F('type_nameid__nameid'))
            .values('id', 'ctime', 'title', 'description', 'source', 'picUrl', 'url', 'commitNumber',
                    'agreeNumber', 'watched', 'type_nameid')
        )
        collected_videos = [
            {**video,
             'picUrl': f"/media/{video['picUrl']}",
             'url': f"/media/{video['url']}",
             'is_liked': Like.objects.filter(username=user, item_id=video['id']).exists(),
             'is_collected': Collect.objects.filter(username=user, item_id=video['id']).exists(),

             }
            for video in collected_videos
        ]
        return JsonResponse({"code": 200, "message": "请求成功", "collected_videos": collected_videos})
    except Exception as e:
        return JsonResponse({"code": 500, "message": f"请求失败，服务器错误: {str(e)}"})

def get_captcha(request):
    new_key = CaptchaStore.generate_key()
    image_url = captcha_image_url(new_key)
    return JsonResponse({"code": 200,'key': new_key, 'image_url': image_url})
class UserRegisterView(APIView):
    def post(self, request):
        serializer = UserInfoSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"code": 200, "message": "注册成功"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CaptchaView(APIView):
    def get(self, request):
        form = CaptchaForm()
        return render(request, 'captcha_form.html', {'form': form})

    def post(self, request):
        form = CaptchaForm(request.POST)
        if form.is_valid():
            return Response({"code": 200, "message": "验证码正确"}, status=status.HTTP_200_OK)
        else:
            return Response({"code": 400, "message": "验证码错误", "errors": form.errors}, status=status.HTTP_400_BAD_REQUEST)
@csrf_exempt
def login(request):
    print( request.POST.get('captcha_1'),request.POST.get('captcha_0'))
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')

            if not username or not password:
                return JsonResponse({'error': '用户名和密码不能为空'}, status=400)

            user = authenticate(request, username=username, password=password)

            if user is not None:
                auth_login(request, user)
                print("登录成功")
                return JsonResponse({
                    'code': 200,
                    'message': '登录成功',
                    'user': user.username,
                    'nickname': user.nickname,
                    'phone': user.phone,
                    'gender':user.gender,
                    'email': user.email,
                    'birthday': user.birthday,
                    'profile': user.profile,
                    'avatar': user.avatar.url if user.avatar else '',
                    'loginip': user.loginip
                })

            else:
                print("用户名或密码错误")
                return JsonResponse({
                    'code':401,
                    'error': '用户名或密码错误'
                })
        else:
            print("验证码错")
            return JsonResponse({
                'code':400,
                'error': '验证码错误',
                'errors': form.errors
            })

def getuserinfo(request):
    if request.method == 'GET':
        username = request.GET.get('username')
        if username:
            try:
                user = UserInfo.objects.get(username=username)
                return JsonResponse({
                    'username': user.username,
                    'phone': user.phone,
                    'email': user.email,
                    'nickname': user.nickname,
                    'profile': user.profile,
                    'avatar': user.avatar.url if user.avatar else '',
                    'loginip': user.loginip
                })
            except UserInfo.DoesNotExist:
                return JsonResponse({'error': '用户不存在'}, status=400)


"""返回视频类型列表"""
def getvediotype(request):
    if request.method == 'GET':
        try:
            vediotype = list(Type.objects.all().values('id', 'name', 'nameid', 'jianjie'))
            print(vediotype)
            return JsonResponse({"code": 200, "message": "请求成功", "vediotype": vediotype})
        except Exception as e:
            print(f"Error occurred: {e}")
            return JsonResponse({"code": 500, "message": "服务器内部错误", "error": str(e)})
    else:
        return JsonResponse({"code": 400, "message": "请求方法错误，仅支持 GET 请求"})



def getvedio(request):
    type_id = request.GET.get('type_id')
    username = request.GET.get('username')
    if not type_id or not username:
        return JsonResponse({"code": 400, "message": "请求失败，参数错误"})

    user = get_object_or_404(UserInfo, username=username)

    try:
        vediolist = list(
            Video.objects.filter(type_nameid=type_id)
            .annotate(annotated_type_nameid=F('type_nameid__nameid'))
            .values('id', 'ctime', 'title', 'description', 'source', 'picUrl', 'url', 'commitNumber',
                    'agreeNumber', 'watched', 'type_nameid')
        )
        vediolist = [
            {**video,
             'picUrl': f"/media/{video['picUrl']}",
             'url': f"/media/{video['url']}",
             'is_liked': Like.objects.filter(username=user, item_id=video['id']).exists(),
             'is_collected': Collect.objects.filter(username=user, item_id=video['id']).exists(),
            }
            for video in vediolist
        ]
        return JsonResponse({"code": 200, "message": "请求成功", "vediolist": vediolist})
    except Type.DoesNotExist:
        return JsonResponse({"code": 400, "message": "请求失败，类型不存在"})


def get_random_videos(request):
    username = request.GET.get('username')
    if not username:
        return JsonResponse({"code": 400, "message": "请求失败，参数错误"})
    user = get_object_or_404(UserInfo, username=username)
    if request.method == 'GET':
        try:
            # 获取所有视频的ID列表
            all_video_ids = list(Video.objects.values_list('id', flat=True))

            # 随机选择10个视频ID
            random_video_ids = random.sample(all_video_ids, min(len(all_video_ids), 10))

            # 根据随机选择的ID获取视频信息
            vediolist = list(
                Video.objects.filter(id__in=random_video_ids)
                .annotate(annotated_type_nameid=F('type_nameid__nameid'))
                .values('id', 'ctime', 'title', 'description', 'source', 'picUrl', 'url', 'commitNumber',
                        'agreeNumber', 'watched', 'type_nameid')
            )
            vediolist = [
                {**video,
                 'picUrl': f"/media/{video['picUrl']}",
                 'url': f"/media/{video['url']}",
                 'is_liked': Like.objects.filter(username=user, item_id=video['id']).exists(),
                 'is_collected': Collect.objects.filter(username=user, item_id=video['id']).exists(),
                 }
                for video in vediolist
            ]
            return JsonResponse({"code": 200, "message": "请求成功", "vediolist": vediolist})
        except Exception as e:
            return JsonResponse({"code": 500, "message": f"请求失败，服务器错误: {str(e)}"})
    else:
        return JsonResponse({"code": 400, "message": "请求方法错误，仅支持 GET 请求"})


@csrf_exempt
def update_user_info(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        user = get_object_or_404(UserInfo, username=username)
        form = UserInfoUpdateForm(request.POST, request.FILES, instance=user)

        if form.is_valid():
            user.gender = form.cleaned_data.get('gender')
            user.birthday = form.cleaned_data.get('birthday')
            form.save()
            return JsonResponse({"code": 200, "message": "信息更新成功", "avatar": user.avatar.url,"nickname":user.nickname,"phone":user.phone,"email":user.email,"profile":user.profile,"gender":user.gender,"birthday":user.birthday})
        else:
            return JsonResponse({"code": 400, "message": "信息更新失败", "errors": form.errors})
    else:
        return JsonResponse({"code": 400, "message": "请求方法错误，仅支持 POST 请求"})